﻿Imports System.Xml
Imports System.IO
Imports System.IO.Ports

Class Window1

    Private Sub AppSettings_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim SettingsWindow As New WindowSettings
        SettingsWindow.ShowDialog()
    End Sub

    Private Sub cmbPresets_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs)
        UI_Control()

    End Sub

    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

        'If a new version of the program is installed, upgrade the settings to continue using them
        If My.Settings.UpgradeSettings Then
            My.Settings.Upgrade()
            My.Settings.UpgradeSettings = False
        End If

        'If the presets file was not found, create it.
        If Not File.Exists(String.Format("{0}\presets.cfg", Environment.CurrentDirectory)) Then
            Dim PresetsXML As XDocument = New XDocument( _
            New XDeclaration("1.0", "utf-8", "yes"), _
            New XComment("Preset File"), _
            New XElement("presets"))

            PresetsXML.Save(String.Format("{0}\presets.cfg", Environment.CurrentDirectory))
        End If
        xmlData.Source = New Uri(String.Format("{0}\presets.cfg", Environment.CurrentDirectory))


        'add the ability to use manual control to the presets dialog
        AddManualControl()


        cmbPresets.SelectedValue = ""


    End Sub

    Private Sub btnSendToTVs_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)

        Dim DeviceHeader As String = "EF" 'Depends on the model of video switcher

        If Not String.IsNullOrEmpty(My.Settings.ComPort) Then


            Dim controllerSerialPort As New SerialPort
            controllerSerialPort.PortName = My.Settings.ComPort
            controllerSerialPort.BaudRate = Convert.ToInt32(My.Settings.BaudRate)
            controllerSerialPort.DataBits = Convert.ToInt32(My.Settings.DataBits)
            controllerSerialPort.Parity = CType([Enum].Parse(GetType(IO.Ports.Parity), My.Settings.Parity), IO.Ports.Parity)
            controllerSerialPort.StopBits = CType([Enum].Parse(GetType(IO.Ports.StopBits), My.Settings.StopBit), IO.Ports.StopBits)

            controllerSerialPort.Open()

            If Not cmbInput1.SelectedIndex = -1 Then
                'Dim xmtBuf() As Byte = {239, Convert.ToInt16(My.Settings.DeviceAddress, 16), 1, cmbInput1.SelectedIndex}
                Dim xmtBuf() As Byte = {Long.Parse(DeviceHeader, Globalization.NumberStyles.HexNumber), Long.Parse(My.Settings.DeviceAddress, Globalization.NumberStyles.HexNumber), &H1, Long.Parse(cmbInput1.SelectedIndex, Globalization.NumberStyles.HexNumber)}
                controllerSerialPort.Write(xmtBuf, 0, xmtBuf.Length)
            End If
            If Not cmbInput2.SelectedIndex = -1 Then
                'Dim xmtBuf() As Byte = {239, Convert.ToInt16(My.Settings.DeviceAddress, 16), 2, cmbInput2.SelectedIndex}
                Dim xmtBuf() As Byte = {Long.Parse(DeviceHeader, Globalization.NumberStyles.HexNumber), Long.Parse(My.Settings.DeviceAddress, Globalization.NumberStyles.HexNumber), &H2, Long.Parse(cmbInput2.SelectedIndex, Globalization.NumberStyles.HexNumber)}
                controllerSerialPort.Write(xmtBuf, 0, xmtBuf.Length)
            End If
            If Not cmbInput3.SelectedIndex = -1 Then
                'Dim xmtBuf() As Byte = {239, Convert.ToInt16(My.Settings.DeviceAddress, 16), 3, cmbInput3.SelectedIndex}
                Dim xmtBuf() As Byte = {Long.Parse(DeviceHeader, Globalization.NumberStyles.HexNumber), Long.Parse(My.Settings.DeviceAddress, Globalization.NumberStyles.HexNumber), &H3, Long.Parse(cmbInput3.SelectedIndex, Globalization.NumberStyles.HexNumber)}
                controllerSerialPort.Write(xmtBuf, 0, xmtBuf.Length)
            End If
            If Not cmbInput4.SelectedIndex = -1 Then
                'Dim xmtBuf() As Byte = {239, Convert.ToInt16(My.Settings.DeviceAddress, 16), 4, cmbInput4.SelectedIndex}
                Dim xmtBuf() As Byte = {Long.Parse(DeviceHeader, Globalization.NumberStyles.HexNumber), Long.Parse(My.Settings.DeviceAddress, Globalization.NumberStyles.HexNumber), &H4, Long.Parse(cmbInput4.SelectedIndex, Globalization.NumberStyles.HexNumber)}
                controllerSerialPort.Write(xmtBuf, 0, xmtBuf.Length)
            End If
            If Not cmbInput5.SelectedIndex = -1 Then
                'Dim xmtBuf() As Byte = {239, Convert.ToInt16(My.Settings.DeviceAddress, 16), 5, cmbInput5.SelectedIndex}
                Dim xmtBuf() As Byte = {Long.Parse(DeviceHeader, Globalization.NumberStyles.HexNumber), Long.Parse(My.Settings.DeviceAddress, Globalization.NumberStyles.HexNumber), &H5, Long.Parse(cmbInput5.SelectedIndex, Globalization.NumberStyles.HexNumber)}
                controllerSerialPort.Write(xmtBuf, 0, xmtBuf.Length)
            End If
            If Not cmbInput6.SelectedIndex = -1 Then
                'Dim xmtBuf() As Byte = {239, Convert.ToInt16(My.Settings.DeviceAddress, 16), 6, cmbInput6.SelectedIndex}
                Dim xmtBuf() As Byte = {Long.Parse(DeviceHeader, Globalization.NumberStyles.HexNumber), Long.Parse(My.Settings.DeviceAddress, Globalization.NumberStyles.HexNumber), &H6, Long.Parse(cmbInput6.SelectedIndex, Globalization.NumberStyles.HexNumber)}
                controllerSerialPort.Write(xmtBuf, 0, xmtBuf.Length)
            End If
            If Not cmbInput7.SelectedIndex = -1 Then
                'Dim xmtBuf() As Byte = {239, Convert.ToInt16(My.Settings.DeviceAddress, 16), 7, cmbInput7.SelectedIndex}
                Dim xmtBuf() As Byte = {Long.Parse(DeviceHeader, Globalization.NumberStyles.HexNumber), Long.Parse(My.Settings.DeviceAddress, Globalization.NumberStyles.HexNumber), &H7, Long.Parse(cmbInput7.SelectedIndex, Globalization.NumberStyles.HexNumber)}
                controllerSerialPort.Write(xmtBuf, 0, xmtBuf.Length)
            End If
            If Not cmbInput8.SelectedIndex = -1 Then
                'Dim xmtBuf() As Byte = {239, Convert.ToInt16(My.Settings.DeviceAddress, 16), 8, cmbInput8.SelectedIndex}
                Dim xmtBuf() As Byte = {Long.Parse(DeviceHeader, Globalization.NumberStyles.HexNumber), Long.Parse(My.Settings.DeviceAddress, Globalization.NumberStyles.HexNumber), &H8, Long.Parse(cmbInput8.SelectedIndex, Globalization.NumberStyles.HexNumber)}
                controllerSerialPort.Write(xmtBuf, 0, xmtBuf.Length)
            End If

            controllerSerialPort.Close()

            lblCurrentVideoScheme.Content = String.Format("Current Scheme: {0}", cmbPresets.SelectedValue.ToString)

        Else
            MsgBox("Could not open RS-232 port, please check your settings.", MsgBoxStyle.Exclamation)

        End If
    End Sub

    Protected Overrides Sub Finalize()
        My.Settings.Save()
        MyBase.Finalize()
    End Sub

    Private Sub btnSavePreset_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)



        Dim presetNameDlg = New PresetNameDialog
        presetNameDlg.ShowDialog()
        If presetNameDlg.DialogResult = True Then

            Dim name As String = presetNameDlg.filename

            Dim presetXML As XElement = <preset name=<%= name %>>
                                            <output1><%= cmbInput1.SelectedIndex %></output1>
                                            <output2><%= cmbInput2.SelectedIndex %></output2>
                                            <output3><%= cmbInput3.SelectedIndex %></output3>
                                            <output4><%= cmbInput4.SelectedIndex %></output4>
                                            <output5><%= cmbInput5.SelectedIndex %></output5>
                                            <output6><%= cmbInput6.SelectedIndex %></output6>
                                            <output7><%= cmbInput7.SelectedIndex %></output7>
                                            <output8><%= cmbInput8.SelectedIndex %></output8>
                                        </preset>

            Dim modifiedXML As XDocument = XDocument.Parse(xmlData.Document.InnerXml.ToString)


            Dim qFindCon As XElement = modifiedXML.Descendants.Elements() _
            .Where(Function(xe) xe.Attribute("name") = name) _
            .FirstOrDefault()

            If Not String.IsNullOrEmpty(qFindCon) Then
                MsgBox("This preset already exists, please choose another name", MsgBoxStyle.Exclamation, "Could not save preset")
                Exit Sub
            End If



            modifiedXML.Element("presets").Add(presetXML)


            Dim qMCon As XElement = modifiedXML.Descendants.Elements() _
            .Where(Function(xe) xe.Attribute("name") = "Manual Control") _
            .FirstOrDefault()

            qMCon.Remove()


            xmlData.Document.InnerXml = modifiedXML.ToString

            modifiedXML.Save(String.Format("{0}\presets.cfg", Environment.CurrentDirectory))

            AddManualControl()


            MsgBox(String.Format("The Preset '{0}' was saved sucessfully.", name), MsgBoxStyle.Information, "Preset Saved")

            cmbPresets.SelectedValue = name
        End If

    End Sub


    Private Sub btnDeletePreset_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
        If cmbPresets.SelectedValue = "Manual Control" Then
            MsgBox("You cannot delete Manual Control.", MsgBoxStyle.Exclamation, "")
        ElseIf cmbPresets.SelectedIndex = -1 Then

        Else
            Dim mbResult = MsgBox(String.Format("Are you sure you wish to delete {0}", cmbPresets.SelectedValue.ToString), MsgBoxStyle.YesNo, "Delete Preset")
            If mbResult = MsgBoxResult.Yes Then

                Dim modifiedXML As XDocument = XDocument.Parse(xmlData.Document.InnerXml.ToString)

                Dim qMCon As XElement = modifiedXML.Descendants.Elements() _
                .Where(Function(xe) xe.Attribute("name") = "Manual Control") _
                .FirstOrDefault()

                qMCon.Remove()


                Dim qPname As XElement = modifiedXML.Descendants.Elements() _
                .Where(Function(xe) xe.Attribute("name") = cmbPresets.SelectedValue.ToString) _
                .FirstOrDefault()

                qPname.Remove()


                xmlData.Document.InnerXml = modifiedXML.ToString

                modifiedXML.Save(String.Format("{0}\presets.cfg", Environment.CurrentDirectory))

                AddManualControl()
            End If
        End If
    End Sub


    Private Sub AddManualControl()
        Dim presetXML As XElement = <preset name="Manual Control">
                                        <output1>-1</output1>
                                        <output2>-1</output2>
                                        <output3>-1</output3>
                                        <output4>-1</output4>
                                        <output5>-1</output5>
                                        <output6>-1</output6>
                                        <output7>-1</output7>
                                        <output8>-1</output8>
                                    </preset>

        Dim modifiedXML As XDocument = XDocument.Parse(xmlData.Document.InnerXml.ToString)
        modifiedXML.Element("presets").AddFirst(presetXML)
        xmlData.Document.InnerXml = modifiedXML.ToString
    End Sub

    Private Sub cmbPresets_SourceUpdated(ByVal sender As Object, ByVal e As System.Windows.Data.DataTransferEventArgs) Handles cmbPresets.SourceUpdated
        UI_Control()
    End Sub

    Private Sub UI_Control()
        'MsgBox(cmbPresets.SelectedValue.ToString)
        Try
            If cmbPresets.SelectedIndex = -1 Then
                btnSendToTVs.IsEnabled = False
                btnDeletePreset.IsEnabled = False

            Else
                btnSendToTVs.IsEnabled = True
                btnDeletePreset.IsEnabled = True
            End If

            If cmbPresets.SelectedValue = "Manual Control" Then
                gridManualControls.IsEnabled = True
                InputExpander.IsExpanded = True
            Else

                gridManualControls.IsEnabled = False
                InputExpander.IsExpanded = False
            End If
        Catch ex As Exception

        End Try

    End Sub

End Class
